package net.bcxuexi.server.stream.inhandle;

import net.bcxuexi.config.Config;
import net.bcxuexi.exception.MyException;
import net.bcxuexi.server.ServerSocketManager;
import net.bcxuexi.server.SocketManager;
import net.bcxuexi.server.model.SocketModel;
import net.bcxuexi.server.stream.StreamData;
import net.bcxuexi.server.stream.outwrap.OutputDataWrap;
import net.bcxuexi.tools.MyLog;

public class DataInputStreamHandler extends AbstractInputStreamHandler{

	@Override
	public void handle() {
		StreamData streamData = null;// 待处理数据

		if (streamData == null) {
			try {
				streamData = take();// 从阻塞队列中取数据，可能会被阻塞
			} catch (InterruptedException e) {
				// 没有取到数据
				return;
			}
		}

		if (streamData == null) {
			MyLog.info("DataInputStreamHandler队列为空，休息！");
			return;
		}
		// 数据处理
		process(streamData);
		try {
			sleep(80);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析协议
	 * @param streamData
	 */
	public void process(StreamData streamData) {
		if(Config.debug){
			String dmsg = new String(streamData.data,0,streamData.total);
			MyLog.info("处理数据连接输入数据流数据:"+dmsg);
		}
		/*
		 * 解析协议
		 * 第0个字节为2:代表数据通信
		 * 第1到8个字节:代表proxy socket的connId
		 * 第9到20个字节:代表内网服务器的4位ip 192168001155
		 * 第21到25个字节:代表内网服务器的端口 如:61235,08080
		 */
		byte[] msg = streamData.data;
		String proxySocketConnId = new String(msg,1,8);
		String innerIp = Integer.valueOf(new String(msg,9,3))+"."+Integer.valueOf(new String(msg,12,3))+"."+Integer.valueOf(new String(msg,15,3))+"."+Integer.valueOf(new String(msg,18,3));
		int innerPort = Integer.valueOf(new String(msg,21,5));
		//找到接收数据的代理连接socket
		SocketModel proxySocketModel = SocketManager.getInstance().findSocketModelByConnId(proxySocketConnId);
		//数据发送到对应代理socket
		if(proxySocketModel!=null&&proxySocketModel.isActive()){
			byte[] data = new byte[streamData.total-26];
			for(int i=0;i<data.length;i++){
				data[i] = msg[26+i];
			}
			if(Config.debug){
				String dmsg = new String(data,0,data.length);
				MyLog.info("------------开始-------------");
				MyLog.info("data数据去掉头部消息后："+dmsg);
				MyLog.info("------------结束-------------");
			}
			StreamData proxyStreamData = new StreamData();
			proxyStreamData.setData(data);
			proxyStreamData.setSocketModel(proxySocketModel);
			proxyStreamData.setTotal(data.length);
			try {
				proxySocketModel.getWriteStream().addData(proxyStreamData);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
